<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体 -->
    <el-card>
      <!-- 标题添加区域 -->
      <el-row
        class="globalHeader"
        style="margin-bottom: 20px; padding-bottom: 45px"
      >
        <el-col :span="4">
          <i class="el-icon-s-grid"></i>
          <span>权限管理</span>
        </el-col>
      </el-row>
      <el-table :data="roleList" style="width: 100%" border stripe>
        <el-table-column label="角色身份">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="拥有权限">
          <template slot-scope="scope">
            <el-button
              type="primary"
              @click="searchAuthority(scope.row.baseIdentity)"
              icon="el-icon-search"
              >查看权限</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="success"
              @click="distributeAuthority(scope.row.baseIdentity)"
              icon="el-icon-setting"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-drawer
      :with-header="false"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="handleClose"
    >
      <el-tree
        ref="treeRef"
        :data="bossAuthority"
        :props="defaultProps"
        default-expand-all
        :default-checked-keys="selectedId"
        node-key="id"
        show-checkbox
      ></el-tree>
      <div style="padding: 20px 10px; overflow: hidden">
        <el-button
          style="float: right; margin: 0 20px"
          type="primary"
          @click="toDistribute"
          >分配</el-button
        >
        <el-button style="float: right" @click="closeDrawer">取消</el-button>
      </div>
    </el-drawer>
    <el-dialog :visible.sync="isShowAuthority" title="拥有权限" @close="closeAuthority">
      <el-row :class="['vcenter', 'bdbottom', 'bdtop']">
        <!-- 渲染一级权限 -->
        <el-col :span="5"
          ><el-tag>{{ managerAuthority.label }}</el-tag
          ><i class="el-icon-caret-right"></i
        ></el-col>
        <el-col :span="19">
          <!-- 渲染二级权限 -->
          <el-row
            v-for="(item2, i2) in managerAuthority.children"
            :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
            style="margin-bottom: 0px"
            :key="item2.id"
          >
            <el-col :span="6">
              <el-tag type="success">
                {{ item2.label }}
              </el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <el-col :span="18">
              <el-tag
                type="warning"
                v-for="item3 in item2.children"
                :key="item3.id"
              >
                {{ item3.label }}
              </el-tag>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      drawer: false,
      isShowAuthority: false,
      roleList: [],
      baseId: this.$store.state.baseId,
      baseIdentity: window.localStorage.getItem('baseIdentity'),
      token: window.localStorage.getItem('token'),
      bossAuthority: [],
      managerAuthority: {},
      references: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      selectedId: [],
      nowSelectedId: 2,
    }
  },
  methods: {
    // 关闭弹窗，重置权限信息
    closeAuthority() {
      this.managerAuthority = {}
    },
    // 点击按钮,完成分配权限
    async toDistribute() {
      const loading = this.$loading({
        lock: true,
        text: '权限分配中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      let ids = []
      ids.push(this.references[0].authorityId)
      keys.forEach((item) => {
        for (let i = 1; i < this.references.length; i++) {
          if (item === this.references[i].id) {
            ids.push(this.references[i].authorityId)
            break
          }
        }
      })
      const { data: res } = await this.$http.put(
        `http://106.75.154.40:9003/function/base/${this.baseId}/${this.nowSelectedId}`,
        {
          functionIdList: ids,
        },
        {
          headers: {
            Authorization: this.token,
          },
        }
      )
      if (res.code === 20000) {
        this.$message.success('角色权限更新成功！！')
      } else {
        this.$message.error('角色权限更新失败！！')
      }
      loading.close()
      // 分配完成清除数组
      this.$nextTick(function () {
        this.$refs.treeRef.setCheckedKeys([])
      })
      this.drawer = false
    },
    // 取消键关闭分配权限树状图
    closeDrawer() {
      this.drawer = false
      this.selectedId = []
      this.$nextTick(() => {
        this.$refs.treeRef.setCheckedKeys([])
      })
      // this.$refs.treeRef.setCheckedKeys([])
    },
    // 关闭树状图
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
          this.selectedId = []
          this.$nextTick(function () {
            this.$refs.treeRef.setCheckedKeys([])
          })
        })
        .catch((_) => {})
    },
    // 查看权限触发函数
    searchAuthority(id) {
      // 传入1，查看拥有权限
      this.lookAuthority(id).then(() => {
        this.isShowAuthority = true
      })
      console.log(this.managerAuthority)
    },
    // 分配权限
    distributeAuthority(id) {
      // 传入2，分配权限
      // 先查询有什么权限
      this.managerAuthority = {}
      this.lookAuthority(id).then(() => {
        // 再去匹配权限,加入id
        this.matchAuthority(id)
        this.nowSelectedId = id
      })
    },
    // 查看权限
    async lookAuthority(id) {
      const { data: res } = await this.$http.get(
        `http://106.75.154.40:9003/function/${this.baseId}/${id}`,
        {
          headers: {
            Authorization: this.token,
          },
        }
      )
      console.log(this.managerAuthority)
      if (id === 2) {
        let tempBossMenu = []
        // 查找老板权限，生成菜单
        res.data.forEach((item) => {
          if (item.remarks === '溯源管理') {
            let referObj = {}
            referObj.authorityId = item.id
            referObj.label = item.remarks
            tempBossMenu = item.children
            this.references.push(referObj)
          }
        })
        console.log(tempBossMenu)
        if (tempBossMenu.length !== 0) {
          tempBossMenu.forEach((item) => {
            // 获取第一层数组所在的序列号
            let num1 = item.sort
            let oneMenuObj = {}
            let referMenuObj = {}
            oneMenuObj.label = item.remarks
            referMenuObj.label = item.remarks
            referMenuObj.id = num1
            referMenuObj.authorityId = item.id
            oneMenuObj.id = num1
            this.references.push(referMenuObj)
            oneMenuObj.children = []
            if (item.children.length !== 0) {
              item.children.forEach((itemChild) => {
                let num2 = tempBossMenu.length
                for (let i = 0; i < num1 - 1; i++)
                  num2 += tempBossMenu[i].children.length
                num2 += itemChild.sort
                let twoMenuObj = {}
                let referMenuTwoObj = {}
                twoMenuObj.label = itemChild.remarks
                twoMenuObj.id = num2
                referMenuTwoObj.label = itemChild.remarks
                referMenuTwoObj.id = num2
                referMenuTwoObj.authorityId = itemChild.id
                this.references.push(referMenuTwoObj)
                oneMenuObj.children.push(twoMenuObj)
              })
            }
            this.bossAuthority.push(oneMenuObj)
          })
        }
        // 树状列表
        console.log(this.bossAuthority)
        // 数组列表
        console.log(this.references)
      } else {
        let tempManager = []
        res.data.forEach((item) => {
          if (item.remarks === '溯源管理') {
            this.managerAuthority.label = item.remarks
            this.managerAuthority.authorityId = item.id
            this.managerAuthority.children = []
            tempManager = item.children
          }
        })
        // 如果溯源管理分支下有权限，则遍历数组
        if (tempManager.length !== 0) {
          // 遍历二级权限
          tempManager.forEach((item) => {
            // 每一个二级权限是有一个对象
            let tempOneObj = {}
            // 该二级权限有标签、权限id、还有分支下的三级权限数组
            tempOneObj.label = item.remarks
            tempOneObj.authorityId = item.id
            tempOneObj.children = []
            // 判断三级权限是否存在
            if (item.children.length !== 0) {
              // 遍历三级权限
              item.children.forEach((itemInner) => {
                // 每一个三级权限是一个对象
                let tempTwoObj = {}
                // 每一个三级权限对象有标签名、权限id
                tempTwoObj.label = itemInner.remarks
                tempTwoObj.authorityId = itemInner.id
                // 将三级权限追加到该父级权限的children数组
                tempOneObj.children.push(tempTwoObj)
              })
            }
            // 将二级权限追加到该父级权限的children数组
            this.managerAuthority.children.push(tempOneObj)
          })
        }
        console.log(this.managerAuthority)
      }
    },
    // 点击分配权限，匹配为selected数组赋值
    matchAuthority(id) {
      console.log(this.selectedId)
      let tempAuthority = this.managerAuthority.children
      console.log(tempAuthority)

      if (tempAuthority != undefined && tempAuthority.length) {
        tempAuthority.forEach((item) => {
          for (let i = 0; i < this.references.length - 1; i++) {
            if (item.label === this.references[i].label) {
              item.id = this.references[i].id
              break
            }
          }
          item.children.forEach((itemInner) => {
            for (let i = 0; i < this.references.length - 1; i++) {
              if (itemInner.label === this.references[i].label) {
                itemInner.id = this.references[i].id
                this.selectedId.push(itemInner.id)
                break
              }
            }
          })
        })
      }
      // setTimeout(() => {
      this.drawer = true
      // }, 1000)
      console.log(this.selectedId)
    },
    // 获取角色列表
    async getRole() {
      const { data: res } = await this.$http.get(
        'http://106.75.154.40:9003/role/base',
        {
          headers: {
            Authorization: this.token,
          },
        }
      )
      if (res.code === 20001) {
        return this.$message.error('角色请求失败！')
      }
      this.roleList = res.data
    },
  },
  created() {
    this.getRole()
    // 先调用，存储老板的权限菜单树
    this.lookAuthority(2)
    // 经理
    // this.lookAuthority(3)
    // // 员工
    // this.lookAuthority(4)
  },
}
</script>

<style lang="less">
.el-tag {
  margin: 7px;
}
.el-drawer__body {
  overflow-y: scroll;
}
.bdtop {
  border-top: 1px dashed #ccc;
}
.bdbottom {
  border-bottom: 1px dashed #ccc;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>